"use client";
import { useGetStatics, useGetTaskDetail } from "@/service/align";
import { useDownResultFile } from "@/service/dowload";
import { baseURL } from "@/service/request/config";
import {
  CheckCircleTwoTone,
  ExclamationCircleTwoTone,
  SendOutlined,
  SyncOutlined,
} from "@ant-design/icons";
import NavigationIcon from "@mui/icons-material/Navigation";
import LoadingButton from "@mui/lab/LoadingButton";
import {
  Box,
  Container,
  Table as MTable,
  Paper,
  Typography,
} from "@mui/material";
import Alert from "@mui/material/Alert";
import { SnackbarCloseReason } from "@mui/material/Snackbar";
import TableBody from "@mui/material/TableBody";
import TableCell from "@mui/material/TableCell";
import TableContainer from "@mui/material/TableContainer";
import TableHead from "@mui/material/TableHead";
import TableRow from "@mui/material/TableRow";
import { useQueryClient } from "@tanstack/react-query";
import { message, PaginationProps, Table, type TableProps } from "antd";
import { useEffect, useRef, useState } from "react";
import CountUp from "react-countup";

interface DataType {
  id: string;
  pid: string;
  status: string;
  workspace: string;
  workspace_dir: string;
  cmd: string;
  finish_time: string;
  update_time: string;
  create_time: string;
  email: string;
}

const columns: TableProps<DataType>["columns"] = [
  {
    title: "Task ID",
    dataIndex: "id",
  },
  // {
  //   title: "Email",
  //   dataIndex: "email",
  //   render: (text) => {
  //     return (
  //       <div
  //         style={{
  //           overflow: "hidden",
  //           textOverflow: "ellipsis",
  //           whiteSpace: "nowrap",
  //           width: "160px",
  //         }}
  //       >
  //         {text}
  //       </div>
  //     );
  //   },
  // },
  {
    title: "Status",
    dataIndex: "status",
    width: 100,
    render: (text) => (
      <div style={{ display: "flex", alignItems: "center" }}>
        <div style={{ marginRight: "7px" }}>
          {text == "success" && <CheckCircleTwoTone twoToneColor="#52c41a" />}
          {text == "pending" && (
            <SendOutlined style={{ color: "rgb(56, 116, 203)" }} />
          )}
          {text == "running" && (
            <SyncOutlined spin style={{ color: "#52c41a" }} />
          )}
          {text == "canceled" && (
            <ExclamationCircleTwoTone twoToneColor="#fbbf24" />
          )}
        </div>
        {text}
      </div>
    ),
  },
  {
    title: "Workspace",
    dataIndex: "workspace",
  },
  {
    title: "Start Time",
    dataIndex: "create_time",
  },
  {
    title: "PID",
    dataIndex: "pid",
    render: (text) => {
      return <div>{text || 0}</div>;
    },
  },
  {
    title: "Finish Time",

    dataIndex: "finish_time",
    render: (text) => {
      return <div>{text || "Not finished yet"}</div>;
    },
  },
];

const formatter: any = (value: number) => <CountUp end={value} separator="," />;

export default function TaskDetailPage({
  params,
}: {
  params: { task_id: string };
}) {
  const [page, setPage] = useState(1);
  const [rows, setRows] = useState<any[]>([]);
  const [status, setStatus] = useState("success");
  const [file_path, setFilePath] = useState("");
  const [isShowEmail, setShowEmail] = useState(false);
  const task_id = params.task_id;
  const {
    isLoading,
    data: taskList,
    isRefetching,
    refetch: refreshTaskDetail,
  } = useGetTaskDetail(task_id);

  const [url, setUrl] = useState("");

  useEffect(() => {
    if (typeof window !== "undefined") {
      if (!url.length) {
        setUrl(window.location.href);
      }
    }
  });

  useEffect(() => {
    if (
      taskList &&
      Array.isArray(taskList.results) &&
      taskList.results.length > 0
    ) {
      setStatus(taskList.results[0].status);
      setRows(taskList.results[0].info);

      if (
        !taskList.results[0].email ||
        taskList.results[0].email == "no-emial@gmail.com"
      ) {
        setShowEmail(true);
      }
      setFilePath(taskList.results[0].result_path);
    }
  }, [taskList]);

  useEffect(() => {
    console.log(rows, "rows");
  });

  const { data: Count, refetch: refreshStatics } = useGetStatics();
  const isRequest = useRef(false);
  const queryClient = useQueryClient();

  const onShowSizeChange: PaginationProps["onShowSizeChange"] = (current) => {
    setPage(current);
  };

  const [open, setOpen] = useState(false);

  useEffect(() => {
    setOpen(true);
  }, []);

  message.config({
    duration: 2,
    maxCount: 2,
  });
  const [messageApi, contextHolder] = message.useMessage();

  const { mutateAsync: downFile, isPending: downloadPending } =
    useDownResultFile();

  const handleDownLoadFile = async () => {
    try {
      await downFile({ file_path });
      const link = document.createElement("a");
      link.target = "_self";
      link.href = `${baseURL}/download_file/file/?file_path=${file_path}`;
      link.click();
      link.remove();
    } catch (err: any) {
      message.error("该文件不存在");
      // } finally {
      //   setFileId(0);
      // }
    }
  };

  const handleClose = (
    event?: React.SyntheticEvent | Event,
    reason?: SnackbarCloseReason
  ) => {
    if (reason === "clickaway") {
      return;
    }

    setOpen(false);
  };

  // useEffect(() => {
  //   const data = queryClient.getQueriesData({ queryKey: ["tasks", page] });
  //   if (data[0][1]) {
  //     refreshTaskList();
  //     refreshStatics();
  //   }
  // }, [page, refreshStatics, refreshTaskList, queryClient]);

  // useEffect(() => {
  //   if (!isRequest.current) {
  //     isRequest.current = true;
  //     refreshTaskList();
  //     refreshStatics();
  //   }
  // }, [refreshTaskList, refreshStatics]);

  // var timestamp = new Date().getTime();
  return (
    <Box>
      {contextHolder}
      {/* <Snackbar
        open={open}
        anchorOrigin={{ vertical: "top", horizontal: "right" }}
        autoHideDuration={6000}
        onClose={handleClose}
      >
        <Alert
          severity="success"
          action={
            <IconButton
              aria-label="close"
              color="inherit"
              size="small"
              onClick={() => {
                setOpen(false);
              }}
            >
              <CloseIcon fontSize="inherit" />
            </IconButton>
          }
        >
          <AlertTitle>Info</AlertTitle>
          <Typography variant="body1">
            Please copy the browser url to check the task status
          </Typography>

          <Typography variant="body1">{url}</Typography>
        </Alert>
      </Snackbar> */}

      <Container
        sx={{
          display: "flex",
          flexDirection: "column",
          pt: { xs: 14, sm: 20 },
          pb: { xs: 8, sm: 12 },
        }}
      >
        <Paper sx={{ padding: "1rem" }}>
          <div
            style={{
              textAlign: "center",
            }}
          >
            <Alert severity="success">
              <div style={{ textAlign: "left" }}>
                The results will appear here once the job complete. You can
                directly download it here or via your email. <br />
              </div>
            </Alert>

            {isShowEmail ? (
              <Alert severity="warning">
                <div style={{ textAlign: "left" }}>
                  IMPORTANT!!! If you have not provided an email just now,
                  please bookmark this page so you can return to it later. This
                  temporary page will be deleted after one week
                </div>
              </Alert>
            ) : (
              <Alert severity="warning">
                <div style={{ textAlign: "left" }}>
                  Emails sent by GMPS may automatically be marked as spam.
                </div>
              </Alert>
            )}

            <Typography
              sx={{ marginTop: "1rem", marginBottom: "1rem" }}
              variant="h5"
              component="div"
            >
              Task{" "}
              <Box component="span" sx={{ color: "primary.main" }}>
                Detail
              </Box>
            </Typography>
            {/* <div
              style={{
                marginBottom: "32px",
              }}
            >
              <Row gutter={7} style={{ width: "100%" }}>
                <Col span={6}>
                  <Statistic
                    title="Success Tasks"
                    value={Count?.success}
                    precision={2}
                    formatter={formatter}
                  />
                </Col>
                <Col span={6}>
                  <Statistic
                    title="Queue Tasks"
                    value={Count?.pending}
                    precision={2}
                    formatter={formatter}
                  />
                </Col>
                <Col span={6}>
                  <Statistic
                    title="Running Tasks"
                    value={Count?.running}
                    precision={2}
                    formatter={formatter}
                  />
                </Col>
                <Col span={6}>
                  <Statistic
                    title="Time Stamps"
                    value={timestamp}
                    precision={2}
                    formatter={formatter}
                  />
                </Col>
              </Row>
            </div> */}
          </div>
          {isLoading && (
            <Table
              columns={columns}
              dataSource={[]}
              loading={isLoading}
              rowKey={"id"}
              pagination={false}
            />
          )}

          {!isLoading && (
            <Table
              columns={columns}
              dataSource={taskList?.results}
              loading={isLoading}
              rowKey={"id"}
              pagination={false}
              expandable={{
                expandedRowRender: (record: any) => (
                  <div
                  // style={{
                  //   display: "flex",
                  //   flexDirection: "column",
                  //   alignItems: "center",
                  // }}
                  >
                    <Typography variant="subtitle1">
                      {" "}
                      <span style={{ color: "#1976d2" }}>
                        {" "}
                        Running Parameters:
                      </span>{" "}
                    </Typography>
                    {
                      <TableContainer
                        component={Paper}
                        style={{
                          marginBottom: "2rem",
                          marginTop: "1rem",
                        }}
                      >
                        <MTable aria-label="simple table">
                          <TableHead>
                            <TableRow>
                              <TableCell>INPUT ID</TableCell>
                              <TableCell>INPUT TYPE</TableCell>
                              <TableCell>PDB</TableCell>
                              <TableCell align="center">CHAIN</TableCell>
                            </TableRow>
                          </TableHead>
                          <TableBody>
                            {record.info.map((row: any) => (
                              <TableRow
                                key={row.id}
                                sx={{
                                  "&:last-child td, &:last-child th": {
                                    border: 0,
                                  },
                                }}
                              >
                                <TableCell>{row.id}</TableCell>
                                <TableCell>{row.type}</TableCell>
                                <TableCell component="th" scope="row">
                                  {row.file_name}
                                </TableCell>
                                <TableCell align="center">
                                  {row.chain}
                                </TableCell>
                              </TableRow>
                            ))}
                          </TableBody>
                        </MTable>
                      </TableContainer>
                    }
                    <Box
                      sx={{
                        marginTop: "1rem",
                        textAlign: "center",
                      }}
                    >
                      <LoadingButton
                        loading={isRefetching}
                        variant="text"
                        onClick={async () => {
                          try {
                            await refreshTaskDetail();
                            messageApi.success("Refresh successfully");
                          } catch (err) {
                            console.log(err);
                            messageApi.warning("Refresh failed");
                          }
                        }}
                        sx={{
                          padding: "0.5rem 2rem",
                          textTransform: "none",
                          marginRight: "1rem",
                        }}
                      >
                        Refresh Status
                      </LoadingButton>
                      <LoadingButton
                        color="primary"
                        disabled={status != "success"}
                        variant="contained"
                        onClick={() => handleDownLoadFile()}
                        sx={{ textTransform: "none" }}
                      >
                        <NavigationIcon sx={{ mr: 1 }} />
                        Download Result
                      </LoadingButton>
                    </Box>
                  </div>
                ),
                defaultExpandAllRows: true,
                defaultExpandedRowKeys: [taskList?.results[0].id],
              }}
            />
          )}

          {/* {taskList?.results && (
            <div
              style={{
                marginTop: "0.5rem",
                display: "flex",
                justifyContent: "center",
              }}
            >
              <Pagination
                onChange={onShowSizeChange}
                defaultCurrent={1}
                current={page}
                showSizeChanger={false}
                total={taskList.count || 0}
              />
            </div>
          )} */}
        </Paper>
      </Container>
    </Box>
  );
}
